package com.bcsp.xml;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;

public class Test7 {
    public static void main(String[] args) throws Exception{
        //使用dom4j
        //获取文件路径
        String path = Test6.class.getClassLoader().getResource("").getPath();

        //b_out.xml
        //准备SAXReader
        SAXReader reader = new SAXReader();
        //读取文档
        Document document = reader.read(new File(path+"b.xml"));
        //获取根节点
        Element root = document.getRootElement();

        Element studentElement = root.addElement("student");
        //添加属性
        studentElement.addAttribute("ID","8");
        //添加子节点
        Element nameElement = studentElement.addElement("name");
        nameElement.setText("马尼拉");
        Element ageElement = studentElement.addElement("age");
        ageElement.setText("22");
        Element genderElement = studentElement.addElement("gender");
        genderElement.setText("girl");

        //格式化
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        //xml输出流
        XMLWriter writer = new XMLWriter(new FileWriter(path+"b_out.xml"),format);
        //输出
        writer.write(document);
        //关闭流
        writer.close();
    }
}
